package org.example.datascreen.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.example.datascreen.eneity.Result;
import org.example.datascreen.eneity.VO.LoginVO;
import org.example.datascreen.eneity.VO.RegisterVO;
import org.example.datascreen.service.Impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    @RequestMapping("/login")
    public Result login(@RequestBody @Validated LoginVO loginVO) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginVO.getUsername(), loginVO.getPassword());
        try {
            subject.login(token);
            return Result.success();
        }
        catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping("/register")
    public Result register(@RequestBody @Validated RegisterVO registerVO) {
        String result = userService.register(registerVO);

        if (result == "1")
            return Result.success();
        else
            return Result.error(result);
    }

    @RequestMapping("/checkLogin")
    public Result checkLogin() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return Result.success();
        }
        else {
            return Result.error("未登录");
        }
    }
}
